import configparser
import os
import chardet  # 检测编码使用的库
import time
import json
import ast
import pandas as pd
import pytest


# 检测文件的编码类型
def detect_encoding(file_path):
    with open(file_path, 'rb') as f:
        result = chardet.detect(f.read())
    return result['encoding']


#配置文件中编写信息
def config_write(path, section, option, value):
    file_path = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), path)
    
    # 检测文件编码
    encoding = detect_encoding(file_path)
    
    config = configparser.ConfigParser()
    config.read(file_path, encoding=encoding)  # 使用检测到的编码读取文件
    
    if not config.has_section(section):
        config.add_section(section)
    
    config.set(section, option, str(value))
    
    # 使用 UTF-8 编码保存文件
    with open(file_path, 'w', encoding='utf-8') as f:
        config.write(f)

def pytest_terminal_summary(terminalreporter):
    # 统计总数量
    _TOTAL = terminalreporter._numcollected
    _PASSED = len(terminalreporter.stats.get('passed', []))
    _FAILED = len(terminalreporter.stats.get('failed', []))
    _ERROR = len(terminalreporter.stats.get('error', []))
    _SKIPPED = len(terminalreporter.stats.get('skipped', []))
    _RERUN = len(terminalreporter.stats.get('rerun', []))
    _TIME = round(time.time() - terminalreporter._sessionstarttime, 2)  # 测试用时，保留2位

    # 将统计数据写入配置文件
    config_write('config/Transaction.ini', '测试统计结果', '用例总计', _TOTAL)
    config_write('config/Transaction.ini', '测试统计结果', '通过数量', _PASSED)
    config_write('config/Transaction.ini', '测试统计结果', '失败数量', _FAILED)
    config_write('config/Transaction.ini', '测试统计结果', '错误数量', _ERROR)
    config_write('config/Transaction.ini', '测试统计结果', '跳过数量', _SKIPPED)
    config_write('config/Transaction.ini', '测试统计结果', '失败重试', _RERUN)
    config_write('config/Transaction.ini', '测试统计结果', '总计用时', _TIME)



#将pytest.main()中参数放置到配置项中
def pytest_addoption(parser):
    parser.addoption("--params", action="store", default=None, help="Params for fixtures")
    


#迭代测试用例
def pytest_generate_tests(metafunc):
    params_str = metafunc.config.getoption("--params")
    params_str=ast.literal_eval(params_str)
    metafunc.parametrize('test_data', params_str['data_dict_list'])
    


